package com.os.reflect;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author Matt
 * @Date 2022-07-05
 * @Desc:
 * @Version V1.0
 */
public class HelloServiceCgLib implements MethodInterceptor {

    private Object target;

    /**
     * 创建代理对象
     * @param target
     * @return
     */
    public Object getInstance(Object target){
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        //回调方法
        enhancer.setCallback(this);
        //创建代理对象
        return enhancer.create();
    }

    //回调方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.err.println("######我是CGLIB的动态代理######");
        //反射方法前调用
        System.err.println("我准备说hello了");
        Object returnObj = methodProxy.invokeSuper(o, objects);
        //反射方法后调用
        System.err.println("我说过hello了");
        return returnObj;
    }
}
